using MediatR;
using PiggyBankCashFlowApi.Delegate.command;
using PiggyBankCashFlowApi.Exception;
using PiggyBankCashFlowApi.Ext;
using PiggyBankCashFlowApi.Repo;

namespace PiggyBankCashFlowApi.Delegate.Handler;

public class DeleteCashFlowHandler(
    CashFlowRepo repo,
    IHttpContextAccessor accessor,
    ILogger<DeleteCashFlowHandler> logger)
    : IRequestHandler<DeleteCashFlowCommand>
{
    public async Task Handle(DeleteCashFlowCommand command, CancellationToken cancellationToken)
    {
        var entity = await repo.GetCashFlowAsync(command.Id);
        if (entity == null)
        {
            throw new ResourceNotFoundException($"$Cash flow Id {command.Id} doesn't exist");
        }

        var userId = accessor.GetUserId();
        if (!userId.Equals(entity.UserId.ToString()))
        {
            throw new ForbiddenException($"Cannot delete cash flow for other user: " +
                                         $"User id {userId} vs cash flow owner id {entity.UserId}");
        }

        var rowsAffected = await repo.DeleteCashFlowAsync(command.Id);
        if (rowsAffected == 0)
        {
            throw new DbOpNotAcceptedException($"Cannot delete cash flow {command.Id}");
        }
    }
}